const express = require('express')
const { WorkOrder, Process, Equipment, Material } = require('../models')
const router = express.Router()

// 获取工单列表
router.get('/workorder', async (req, res) => {
  try {
    const { page = 1, limit = 10, status, productName } = req.query
    
    const where = {}
    if (status) where.status = status
    if (productName) where.productName = { $like: `%${productName}%` }
    
    const workOrders = await WorkOrder.findAndCountAll({
      where,
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] },
        { model: Process, as: 'process', attributes: ['name', 'code'] },
        { model: Equipment, as: 'equipment', attributes: ['name', 'code'] }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    res.json({
      data: workOrders.rows,
      pagination: {
        total: workOrders.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取工单列表错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 创建工单
router.post('/workorder', async (req, res) => {
  try {
    const workOrder = await WorkOrder.create(req.body)
    
    // 这里可以添加实时通知逻辑
    // io.to('production_room').emit('new_work_order', workOrder)
    
    res.json({ message: '工单创建成功', data: workOrder })
  } catch (error) {
    console.error('创建工单错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新工单
router.put('/workorder/:id', async (req, res) => {
  try {
    const { id } = req.params
    const workOrder = await WorkOrder.findByPk(id)
    
    if (!workOrder) {
      return res.status(404).json({ message: '工单不存在' })
    }
    
    await workOrder.update(req.body)
    
    // 实时通知更新
    // io.to('production_room').emit('work_order_updated', workOrder)
    
    res.json({ message: '工单更新成功', data: workOrder })
  } catch (error) {
    console.error('更新工单错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 开始工单
router.post('/workorder/:id/start', async (req, res) => {
  try {
    const { id } = req.params
    const workOrder = await WorkOrder.findByPk(id)
    
    if (!workOrder) {
      return res.status(404).json({ message: '工单不存在' })
    }
    
    if (workOrder.status !== 'pending') {
      return res.status(400).json({ message: '工单状态不正确' })
    }
    
    await workOrder.update({
      status: 'running',
      startTime: new Date()
    })
    
    res.json({ message: '工单开始成功', data: workOrder })
  } catch (error) {
    console.error('开始工单错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 完成工单
router.post('/workorder/:id/complete', async (req, res) => {
  try {
    const { id } = req.params
    const { actualQuantity } = req.body
    
    const workOrder = await WorkOrder.findByPk(id)
    
    if (!workOrder) {
      return res.status(404).json({ message: '工单不存在' })
    }
    
    if (workOrder.status !== 'running') {
      return res.status(400).json({ message: '工单状态不正确' })
    }
    
    const startTime = new Date(workOrder.startTime)
    const endTime = new Date()
    const actualDuration = Math.floor((endTime - startTime) / (1000 * 60))
    
    await workOrder.update({
      status: 'completed',
      actualQuantity,
      endTime,
      actualDuration
    })
    
    // 这里可以触发库存扣减等后续操作
    
    res.json({ message: '工单完成成功', data: workOrder })
  } catch (error) {
    console.error('完成工单错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取工艺列表
router.get('/process', async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query
    
    const processes = await Process.findAndCountAll({
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    res.json({
      data: processes.rows,
      pagination: {
        total: processes.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取工艺列表错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 创建工艺
router.post('/process', async (req, res) => {
  try {
    const process = await Process.create(req.body)
    res.json({ message: '工艺创建成功', data: process })
  } catch (error) {
    console.error('创建工艺错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取设备列表
router.get('/equipment', async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query
    
    const where = {}
    if (status) where.status = status
    
    const equipment = await Equipment.findAndCountAll({
      where,
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    res.json({
      data: equipment.rows,
      pagination: {
        total: equipment.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取设备列表错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 创建设备
router.post('/equipment', async (req, res) => {
  try {
    const equipment = await Equipment.create(req.body)
    res.json({ message: '设备创建成功', data: equipment })
  } catch (error) {
    console.error('创建设备错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

module.exports = router
